var sbold = /<b>/gi;
var ebold = /<\/b>/gi;
var currobj_id;
var load = false;

var xmlhttp;
var response = '';
var sep = ',';
var currentid;
var succ = 1;

$( addnew );


$(document).ready(function() {
	$('.selectMenu2').css("width", "200px");
	$('.selectMenu3').css("width", "300px");

	$('#breadcrumb').css("font-size", "1em");

	$('a#CNTMTG').click(function(){
	url = $(this).attr("href");
		var ChiTiet=document.getElementById('ttChiTiet').innerHTML;
		var LoaiTien=document.getElementById('ttLoaiTien').innerHTML;
		var Nam=document.getElementById('ttNam').innerHTML;
		url = url + "?ChiTiet="+ChiTiet+"&&Nam="+Nam+"&&LoaiTien="+LoaiTien;
		$(this).attr('href',url);
	});

	$('input#cancel').click(function(){
		url = $('a#CNTMTG').attr("href");
		var ChiTiet=document.getElementById('ttChiTiet').innerHTML;
		var LoaiTien=document.getElementById('ttLoaiTien').innerHTML;
		var Nam=document.getElementById('ttNam').innerHTML;
		url = url + "?ChiTiet="+ChiTiet+"&&Nam="+Nam+"&&LoaiTien="+LoaiTien;
		location.href = url;

	});

	//$("table#mymain").css("background-color", "#D1E5EB");
	//$("table#head td").css("background-color", "LightGoldenRodYellow");

	//$("table#mymain").css("border", "1px dotted #6E7FC9");
	//$("table#mymain td").css("border", "1px dotted black");
	//$("table#myDetail td").css("border", "1px dotted #6E7FC9");
	$("td.value").css("text-align", "left");


	//$("table#myDetail").css("border", "1px solid #6E7FC9");
	//$("table#myDetail th").css("background-color", "Silver ");
	//$("table#myDetail th").css("color", "RoyalBlue");

	//$("th").css("border", "1px dotted #6E7FC9");

	//$("table#myTotal").css("border", "1px solid black");
	$("table#myTotal td").css("border", "1px solid white");

	//$('.actiondelrow').css("font-size", "0.8em");

	$('.css_corner').css("border-radius", "15px");
	$('.css_corner').css("-moz-border-radius", "21px");
	$('.css_corner').css("-webkit-border-radius", "21px");
	$('.css_corner').css("border", "thin solid #DDDDD0");
	$('.css_corner').css("text-align", "center");
	//$('.css_corner').css("background-color", "#D1E5EB");
	$('.css_corner').css("color", "#9C4147");
	$('.css_corner').css("font-size", "0.8em");


	//$('.title').css("font-family", "ABeeZee") ;
	//$('.title').css("line-height", "1em") ;
	//$('.title').css("font-size", "2em") ;
	//$('.title').css("color", "#458B74") ;
	//$('.title').css("text-shadow", "4px 2px 4px #C2C2C2") ;


	$("#isstate").focusout(function(){
		var states = ['PA', "CA"] // of course you will need to add more
		var in_array = $.inArray($("#isstate").val().toUpperCase(), states);
		if (in_array == -1) {
			document.forms['CTTMTG'].elements['isstate'].focus();
		}
	});

	$( "#ngct" ).datepicker({dateFormat:"dd/mm/yy"});
	$( "#fNgay1" ).datepicker({dateFormat:"dd/mm/yy"});
	$( "#fNgay2" ).datepicker({dateFormat:"dd/mm/yy"});
	$( ".datepicker" ).datepicker({dateFormat:"dd/mm/yy"});
	


	$("input").keydown(function(){
		//alert(event.keyCode );
		var self = $(this)
		  , form = self.parents('form:eq(0)')
		  , focusable
		  , next
		  ;
		if (event.keyCode == 13) {
			focusable = form.find('input').filter(':text');
			next = focusable.eq(focusable.index(this)+1);
			if (next.length) {
				//alert(event.keyCode );
				next.focus();
			} else {
			}
			return false;
		}

		
	});
	
	var validator = $("#CTTMTG").validate();
	jQuery("#isstate").blur(function() {

		var states = ['PA', "CA"] // of course you will need to add more
		var in_array = $.inArray(value.toUpperCase(), states);
		if (in_array == -1) {
			return false;
		}else{
			return true;
		}
	});

	jQuery.validator.addMethod('integer', function (value, element, param) {
        return (value != 0) && (value == parseFloat(value, 10));
    }, 'Please enter a non zero integer value!');

	 
});

function DMTraCuu()
{
}

function LoadForm_add(sdong){
	//$('body').css("font-size", "0.8em");

	for (i= 1; i<sdong; i++)
	{
		addnewrow_add();
	}
	document.getElementById("soct").focus();
	
}

function LoadForm_edit(sdong, matk, tkduss, macttkduss, sotienvnss, sotienntss, diengiaiss, urlGettendmTK,urlGettendmDV ){
	//$('body').css("font-size", "0.8em");
    $('input#print').attr("disabled", false);
	tkdus = tkduss.split(",,,");
	macttkdus = macttkduss.split(",,,");
	sotienvns = sotienvnss.split(",,,");
	sotiennts = sotienntss.split(",,,");
	diengiais = diengiaiss.split(",,,");
	

	document.getElementById("soct").focus();

	// doc du lieu dong 0
	var x=document.getElementById('myDetail');
	var sele1 = x.rows[2].getElementsByTagName('select')[0];
	$("#"+sele1.id).val("_"+tkdus[0]);
	changeMa(sele1.id, urlGettendmTK)

	var sele1 = x.rows[2].getElementsByTagName('select')[1];
	$("#"+sele1.id).val("_"+macttkdus[0]);
	changeMaCTTK(sele1.id, urlGettendmDV)

	var cot = 0;
	if (sotienntss !=-1)
	{
		var input1 = x.rows[2].getElementsByTagName('input')[cot];
		cot = cot +1;
		input1.value = 	addCommas(sotiennts[0]);

	}

	var input1 = x.rows[2].getElementsByTagName('input')[cot];
	cot = cot +1;
	{//sotienvn
		input1.value = 	addCommas(sotienvns[0]);

	}

	var input1 = x.rows[2].getElementsByTagName('input')[cot];
	cot = cot+1
	{//sotienvn
		input1.value = diengiais[0];
	}


	tongvn = parseFloat(sotienvns[0]);
	if (isNaN(tongvn))
	{
		tongvn =0;
	}

	if (sotienntss ==-1)
	{
		for (i= 1; i<sdong; i++)
		{
			addnewrow_edit(tkdus[i], macttkdus[i], 0, sotienvns[i], diengiais[i], -1);
			stvn = parseFloat(sotienvns[i]);
			if (!isNaN(stvn))
			{
				tongvn += stvn;
				
			}
		}
		document.getElementById('total').innerHTML = addCommas(tongvn); 

	}
	else
	{
		tongnt = parseFloat(sotiennts[0])*100;
		if (isNaN(tongnt))
		{
			tongnt =0;
		}


		for (i= 1; i<sdong; i++)
		{
			addnewrow_edit(tkdus[i], macttkdus[i], sotiennts[i], sotienvns[i], diengiais[i],0);
			stvn = parseFloat(sotienvns[i]);
			if (!isNaN(stvn))
			{
				tongvn += stvn;
				
			}
			stnt = parseFloat(sotiennts[i])*100;
			//tongnt = 0,3+ 0,16;
			if (!isNaN(stnt))
			{
				tongnt += stnt;
			}
		}
	document.getElementById('total').innerHTML = addCommas(tongvn); 
	document.getElementById("totalNT").innerHTML = addCommas(tongnt/100); 
	}


	for (i= 1; i<sdong; i++)
	{
		var sele1 = x.rows[2+i].getElementsByTagName('select')[0];
		changeMa(sele1.id, urlGettendmTK);
		var sele1 = x.rows[2+i].getElementsByTagName('select')[1];
		changeMaCTTK(sele1.id, urlGettendmDV);
	}



	document.getElementById("soct").focus();
}

function jgetDV(pkq, url)
{
	if (currobj_id.indexOf('chitiettkdu')==0)
	{
		pmadv = pkq.split('::');
		pma = pmadv[0];
		$("#" + currobj_id).val(pma);
		HideDM();
		changeMaCTTK(currobj_id, url);
	}
	return;
}


function RefeshDM()
{	var e = document.getElementById("DM");
	var ma = e.options[e.selectedIndex].value;
	if (ma == 0)
	{
		document.getElementById('danhmucTK').style.display = 'none';
		document.getElementById('danhmucDV').style.display = 'block';
	}
	else if (ma == 1)
	{
		document.getElementById('danhmucTK').style.display = 'block';
		document.getElementById('danhmucDV').style.display = 'none';

	}
}


function zRefeshDM(danhmucs, tendm)
	{
		danhmuc = danhmucs.split(",,,,,");
		document.getElementById('danhmuc').innerHTML  = "<b>"+tendm+"</b><br>";
		for (i = 0; i < danhmuc.length ; ++i) 
		{ 
			document.getElementById('danhmuc').innerHTML  = document.getElementById('danhmuc').innerHTML + "<br>"+ danhmuc[i];
		}
		document.getElementById('danhmuc').innerHTML  = document.getElementById('danhmuc').innerHTML + "<br>";

	}

function refreshDMDV(letter, url)
{
	url = url+ "?dmdv_initial="+ letter;
	jQuery.ajax({
       type: "POST",
       url: url,
       cache: false,
       success: function(response)
       {
		   //alert(response);
		   document.getElementById('danhmucDV_ND').innerHTML = "Các Đơn vị bắt đầu là <b>" + letter+ "</b>:<br>(Nhấn CRL+F để tìm kiếm)<hr>"+ response;
		   
       },
	
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
     });


}


function jgetTK(pkq, url)
{
	alert(pkq+ url+ currobj_id);
	if (currobj_id.indexOf('tkdu')==0)
	{

		pma = pkq.split('::');
		pma = pma[0];
		$("#" + currobj_id).val(pma);
		HideDM();
		changeMa(currobj_id, url);
	}
	return;
}

function jgetmaTK(pma, pten)
{
	if (currobj_id.indexOf('tkdu')==0)
	{
		var dd = document.getElementById(currobj_id);
		for (var i = 0; i < dd.options.length; i++) {
			if (dd.options[i].text === pma) {
				dd.selectedIndex = i;
				break;
			}
		}
		// lay ra ten 
		var x= dd.parentNode;
		var a = x.getElementsByTagName('div')[0];
		a.innerHTML = pten;
	}

}


function jgetmaDV(pma, pten)
{
	if (currobj_id.indexOf('chitiettkdu')==0)
	{
		var dd = document.getElementById(currobj_id);
		for (var i = 0; i < dd.options.length; i++) {
			if (dd.options[i].text === pma) {
				dd.selectedIndex = i;
				break;
			}
		}
		// lay ra ten 
		var x= dd.parentNode;
		var a = x.getElementsByTagName('div')[0];
		a.innerHTML = pten;
	}

}


function SetCur(pObj, tkdvs, tkcps)
{
	currobj_id = pObj
	return;

	if (currobj_id.indexOf('tkdu')==0)
	{
		document.getElementById('danhmucTK').style.display = 'block';
		document.getElementById('danhmucDV').style.display = 'none';
	}
	else if (currobj_id.indexOf('chitiettkdu')==0)
	{
		idmatk = currobj_id.replace("chitiettkdu", "tkdu");
		matk = document.getElementById(idmatk).value;
		if (matk.length == 0 )
		{
			alert("Ban chua nhap MATK!" );
			document.getElementById(idmatk).focus();
			return;
		}
		p = tkdvs.indexOf(matk+"-"); 

		if (p=0 || tkdvs.substr(p-1,1) == '-')
		{

			document.getElementById('danhmucTK').style.display = 'none';
			document.getElementById('danhmucDV').style.display = 'block';
		}
		else
		{
			document.getElementById('danhmucTK').style.display = 'none';
			document.getElementById('danhmucDV').style.display = 'none';


		}
	}
	else
	{
		document.getElementById('danhmucTK').style.display = 'none';
		document.getElementById('danhmucDV').style.display = 'none';
	}


}



function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
	//alert(charCode);
	if (charCode == 46 )
	{
		return true;
	}
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}    


function EnterMa(id, idHint, aData)
{
	var stk, astk, pos;
	var kq = document.getElementById(id).value.toUpperCase();
	dmtk = aData.split(",");
	
	for (i = 0; i < dmtk.length; ++i) 
	{ 
		stk = dmtk[i].toUpperCase();
		pos = stk.indexOf(kq);
		if (pos==0)
		{
			astk = stk.split("-");
			document.getElementById(idHint).innerHTML  =  astk[1];
			return;
		}
	}
	document.getElementById(idHint).innerHTML  =  "*M&#227; nh&#7853;p sai ";
}


function close_window() {
  if (confirm("Ban muon ngung cap nhat?")) {
    close();
  }
}



function OnBlurInput(aData, v)
{

	var a = aData.split(",");

	var i;
	var co = 0;
	for (i=0; i<a.length; i++) 
		{ if (a[i].indexOf(v) >=0) 
			{
			co = 1;
			break;
			}

		}

		
	if (co == 0) {
		document.forms['CTTMTG'].elements['isstate'].focus();
	}

}

function addnew() {

  // Insert a DOM element object
  $('#myDiv').load('http://localhost/duoctu3/templates/acctKT/SDTTForm_add.php');
  

  var newPara = document.createElement( 'p' );
  var newParaText = document.createTextNode( "Here's a DOM element" );
  newPara.appendChild( newParaText );
  $('#myDiv').before( newPara );

  // Insert a string of HTML
  $('#myDiv').before( "<p>kkkk</p>" );

  // Insert a jQuery object
  $('#myDiv').before( $("<p>Here's a jQuery object</p>") );

  // Insert the output from a callback function
  $('#myDiv').before( sayHello );

  function sayHello() {
    return "<p>Hello! This is the output from a callback function</p>";
  }

  //onclick='$("#myTable > tbody").append("{$newrow}");'


}

 function addnewrow_edit(tkdus, macttkdus, sotiennts, sotienvns, diengiais, sotienntss)
 {
	// alert(sotienntss);
    var x=document.getElementById('myDetail');
    var new_row = x.rows[2].cloneNode(true);
	
    var len = x.rows.length;
	var ncot = new_row.cells.length;

	var sele1 = new_row.cells[0].getElementsByTagName('select')[0];
	sele1.id += len;
	
	//tkdus = "_"+tkdus;
	//$("#"+sele1.id).val("_1122"); khoong dungduoc 
	{//tkdus
		for (var i = 0; i < sele1.options.length; i++) {
			if ((sele1.options[i].text).indexOf(tkdus) == 0) {
				sele1.selectedIndex = i;
				break;
			}
		}
	}


	sele1 = new_row.cells[1].getElementsByTagName('select')[0];
	sele1.id += len;
	//$("#"+sele1.id).val("_"+macttkdus);
	{//macttkdu
		for (var i = 0; i < sele1.options.length; i++) {
			if ((sele1.options[i].text).indexOf(macttkdus) == 0) {
				sele1.selectedIndex = i;
				break;
			}
		}
	}

	var cot = 2;
	if (sotienntss !=-1)
	{
		var input1 = new_row.cells[cot].getElementsByTagName('input')[0];
		cot = cot +1;
		input1.value = 	addCommas(sotiennts);

	}

	var input1 = new_row.cells[cot].getElementsByTagName('input')[0];
	cot = cot +1;
	{//sotienvn
		input1.id += len;
		input1.value = addCommas(sotienvns) ;
	}

	var input1 = new_row.cells[cot].getElementsByTagName('input')[0];
	cot = cot+1;
	{//sotienvn
		input1.id += len;
		input1.value = diengiais;
		
	}

	var a1 = new_row.getElementsByTagName('a')[0];
	a1.id += len;

	var inp1 = new_row.getElementsByTagName('div')[0];
	inp1.innerHTML= '';

	var inp1 = new_row.getElementsByTagName('div')[1];
	inp1.innerHTML= '';

    x.appendChild( new_row );
 }

 function addnewrow_add()
 {
	
    var x=document.getElementById('myDetail');
    var new_row = x.rows[2].cloneNode(true);
	
    var len = x.rows.length;
	var ncot = new_row.cells.length;

	var sele1 = new_row.cells[0].getElementsByTagName('select')[0];
	sele1.id += len;
	sele1 = new_row.cells[1].getElementsByTagName('select')[0];
	sele1.id += len;

	for (i = 2 ; i< ncot - 2; i++)
	{
		var inp1 = new_row.cells[i].getElementsByTagName('input')[0];
		inp1.id += len;
		inp1.value = '';
	}
		var inp1 = new_row.cells[ncot-2].getElementsByTagName('input')[0];
		inp1.id += len;
	
	var a1 = new_row.getElementsByTagName('a')[0];
	a1.id += len;

	var inp1 = new_row.getElementsByTagName('div')[0];
	inp1.innerHTML= '';

	var inp1 = new_row.getElementsByTagName('div')[1];
	inp1.innerHTML= '';

    x.appendChild( new_row );
	sele1 = new_row.cells[0].getElementsByTagName('select')[0];
	sele1.focus();

 }



function delerow(rId, dong, cnt, cvn)
 {
	var x=document.getElementById('myDetail');
	var a = x.getElementsByTagName('a');
	for (i=0;i<a.length ; i++)
	{
		if (rId == a[i].id)
		{
			row = i + dong;
			if (row <=dong)
			{
				alert("Khong xoa duoc!");
			}
			else
				if (confirm("Ban muon xoa dong nay khong?"))
				{
					document.getElementById("myDetail").deleteRow(row);
					tinhtongAll(x, dong, cnt, cvn, null);
				}
		}
	}
	return;
 }


function tinhtongAll(x, dong, cotnt, cotvn, tigia)
{
	if (x==null)
	{
		x=document.getElementById('myDetail');
	}
    var len = x.rows.length;

	if (tigia!==null)
	{
		tigia = document.getElementById('tygia').value;
		tigia = parseFloat(tigia.replace(/,/g, ""));
	}
	var totalvn = 0; var totalnt = 0;

	for (i = dong ; i< len; i++)
	{
		var row = x.rows[i];
		var val = row.getElementsByTagName("input");

		if (cotnt >=0)
		{
			st = val[cotnt].value;
			stnt = parseFloat(st.replace(/,/g, ""))*100;
			if (stnt >0 )
			{
				totalnt +=  stnt;
			}
		}

		st = val[cotvn].value;
		if (tigia !== null)
		{
			stvn = stnt * tigia;
			val[cotvn].value = addCommas(stvn);

		}
		else
		{
			stvn = parseFloat(st.replace(/,/g, ""));
		}

		if (stvn >0 )
		{
			totalvn +=  stvn
		}

	}

	document.getElementById("totalNT").innerHTML = addCommas(totalnt/100); 
	document.getElementById("total").innerHTML = addCommas(totalvn); 

}



function addnewrow2()
{
rowNum =1;
var row = '<p id="rowNum'+rowNum+'">Item quantity: <input type="text" name="qty[]" size="4" value="'+frm.add_qty.value+'"> Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#myTable').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}



function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}

function zShowMATK(str)
{
loadXMLDoc("gethint.php?q="+str,function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  });
}

function zzShowMATK(str)
{
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="iiiiiiii";
  return;
  }

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","http://localhost/duoctu3/classes/acct/js/gethint.php?q="+str,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}


function validNgay(nStr, nid, year)
{

//	var dt1   = parseInt(nStr.substring(0,2));
//	var mon1  = parseInt(nStr.substring(3,5));
//	var yr1   = parseInt(nStr.substring(6,10));
//	var ngay = new Date(yr1, mon1-1, dt1);
//
//	if (isNaN(ngay))
//	{
//		document.getElementById(nid).focus();
//		return;
//	}

		//document.getElementById(nid).value  = addCommas(nStr);
}


function validTyGia(nStr, nid)
{
	document.getElementById(nid).value  = addCommas(nStr);
}


function validSoTienVN(nStr, nid, ncot)
{
	document.getElementById(nid).value  = addCommas(nStr);
	tinhtong("total", ncot);

}


function validSoTienNT(nStr, nid, ncot)
{
	// tinh lai so tien VN:
	//var st1 = parseFloat(st.replace(/,/g, ""));

	var nidVN = nid.replace('nt', 'vn');

	var sotienvn = parseFloat(document.getElementById(nidVN).value) ;
	if (sotienvn == 0 || isNaN(sotienvn))
	{
		var sotiennt = document.getElementById(nid).value ;
		sotiennt = parseFloat(sotiennt.replace(/,/g, ""));
		var tygia = document.getElementById("tygia").value;
		if (isNaN(tygia))
		{
			tygia = tygia.replace(/,/g, "");
			tygia = parseInt(tygia);
		}
		else if (tygia == "")
		{
			tygia = 1;
		}
		
		//sotienvn = addCommas(tygia * sotiennt);
		sotienvn = parseInt(tygia * sotiennt);
		sotienvn = addCommas(sotienvn);
		document.getElementById(nidVN).value  = sotienvn ;
	}

	document.getElementById(nid).value  = addCommas(nStr);
	tinhtong("totalNT", ncot);
	
}


function addCommas(nStr, nid)
{    
	if (isNaN(nStr))
	{
		return nStr;
	}
	nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
	//alert(nStr+"---"+x2);
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + sep + '$2');
    }
    return x1 + x2;
}

function tinhtong(loaitong, ncot)
{   
    var x=document.getElementById('myDetail');
    var len = x.rows.length;
	var total = 0;
	for (i = 2 ; i< len; i++)
	{
		var row = x.rows[i];
		//var cell= row.cells;
		var val = row.getElementsByTagName("input");
		//if (val.length >3)
		{
			var st = val[ncot].value;
			var st1 = parseFloat(st.replace(/,/g, ""));
			if (st1 >0 )
			{
				total +=  st1
			}
		}
	}

	document.getElementById(loaitong).innerHTML = addCommas(total); 

}

function ShowMATK(q,dmtk)
{
	if (q.length==0)
	  { 
	  document.getElementById("txtHint").innerHTML="H&#227;y nh&#7853;p M&#227; TK";
	  return;
	  }

	var hint="";
	var nhap="";
	var stk = "";

	dmtk = dmtk.split(",");
	q=q.toLowerCase(); 
	len=q.length;
	var pos = -1;

		
	for (i = 0; i < dmtk.length; ++i) 
	{ 
		stk = dmtk[i].toLowerCase();
		pos = stk.indexOf(q);
		if (pos ==0)
		{
			if (hint=="")
			{
				hint = "<a onclick=\"getMATK('" + dmtk[i]+  "')"+ "\">"+dmtk[i]+"</a>";
			}
			else
			{
			hint = hint+"</br><a onclick=\"getMATK('" + dmtk[i]+  "')"+ "\">"+dmtk[i]+"</a>";
			
			}
		}
	}
	document.getElementById("txtHint").innerHTML=hint;

}

function getMATK(q)
{
	document.getElementById("matk").value=q;
	document.getElementById("txtHint").innerHTML="";

}



function ShowHint(q,aData, txtHint, txtMa, ngandong )
{
	var x=document.getElementById(txtMa);
	x = x.parentNode;
	var a = x.getElementsByTagName('div')[0];


	if (q.length==0)
	  { 
	  //document.getElementById(txtHint).innerHTML="H&#227;y nh&#7853;p M&#227; ";
	  return;
	  }

	var hint="";
	var ten = "";
	var stk = "";
	var ngandong = '&nbsp; &nbsp; &nbsp;'

	//aData = aData.replace(sbold, "");
	//aData = aData.replace(ebold, "");

	dmtk = aData.split(",");
	q=q.toLowerCase(); 
	var pos = -1;

	var nhap = "";
	for (i = 0; i < dmtk.length; ++i) 
	{ 
		stk = dmtk[i].toLowerCase();
		//stk = stk.replace(sbold, "");
		//stk = stk.replace(ebold, "");
		nhap = nhap+ stk;

		pos = stk.indexOf("<b>"+q);
		if (pos ==0)
		{
			if (hint=="")
			{
				hint = "<i>"+dmtk[i]+"</i>";
			}
			else
			{
			//hint = hint+ngandong+ "<a onclick=\"getMA('" + dmtk[i]+  "','"+txtMa+"',"+ "'"+ txtHint+"')"+ "\">"+dmtk[i]+"</a>";
				hint = hint+ngandong+ "<i>"+dmtk[i]+"</i>";

			}
		}
	}
	//alert(hint);


	if (hint=="")
	{
		for (i = 0; i < dmtk.length; ++i) 
		{ 
			if (hint=="")
			{
				hint = "<i>"+dmtk[i]+"</i>";
			}
			else
			{
				hint = hint+ngandong+ "<i>"+dmtk[i]+"</i>";

			}
		}
	}

	//document.getElementById(txtHint).innerHTML=hint;
	a.innerHTML= hint;
}



function zShowHintCTTK(q,aDataLoaiTK, aDataDV, aDataCP, txtMa, ngandong )
{
	
	var hint="";
	var ten = "";
	var stk = "";
	var ngandong = '&nbsp; &nbsp; &nbsp;'
	var idmatk, idsotienvn ;
	var idmatk_value ;


	var x=document.getElementById(txtMa);
	x = x.parentNode;
	var a = x.getElementsByTagName('div')[0];

	if (q.length==0)
	  { 
	  a.innerHTML="";

	  return;
	  }

	/// loai tai khoan:
	//lay tai khoan du:
	idmatk = txtMa.replace("chitiettkdu", "tkdu");
	idsotienvn = txtMa.replace("chitiettkdu", "sotienvn");

	idmatk_value =document.getElementById(idmatk).value;

	if (idmatk_value.length == 0)
	{
		document.getElementById(txtMa).value = "";
		document.getElementById(idmatk).focus();
		a.innerHTML= "**Mã TK kh&#244;nng &#273;&#432;&#7907;c tr&#7889;ng";
		return;
	}

	/// lay danh muc tuong ung
	alert(idmatk_value);

	dmtkLoai = aDataLoaiTK.split(",");
	var inpos = dmtkLoai.indexOf(idmatk_value+"-DV");
	if (inpos>=0)
	{
		dmtk = aDataDV.split(",");
	}
	else 
	{
		inpos = dmtkLoai.indexOf(idmatk_value+"-CP");
		if (inpos>=0)
		{
			dmtk = aDataCP.split(",");
		}
		else
		{
			document.getElementById(txtMa).value = "";
			//document.getElementById(idsotienvn).focus();
			a.innerHTML= "";
			return;

		}

	}

	q=q.toLowerCase(); 
	var pos = -1;

	for (i = 0; i < dmtk.length; ++i) 
	{ 
		stk = dmtk[i].toLowerCase();
		pos = stk.indexOf(q);
		if (pos ==0)
		{
			if (hint=="")
			{
				hint = "<i>"+dmtk[i]+"</i>";
			}
			else
			{
			//hint = hint+ngandong+ "<a onclick=\"getMA('" + dmtk[i]+  "','"+txtMa+"',"+ "'"+ txtHint+"')"+ "\">"+dmtk[i]+"</a>";
				hint = hint+ngandong+ "<i>"+dmtk[i]+"</i>";

			}
		}
	}
	
	if (hint=="")
	{
		for (i = 0; i < dmtk.length; ++i) 
		{ 
			if (hint=="")
			{
				hint = "<i>"+dmtk[i]+"</i>";
			}
			else
			{
				hint = hint+ngandong+ "<i>"+dmtk[i]+"</i>";

			}
		}
	}

	//document.getElementById(txtHint).innerHTML=hint;
	a.innerHTML= hint;
}



function changeMaCTTK(id, url)
{

	var e = document.getElementById(id);
	var ma = $("#" + id).val();
	ma = ma.substring(1);

	url = url+ "?dmdv_madv="+ ma;
	x = e.parentNode;
	var a = x.getElementsByTagName('div')[0];

	jQuery.ajax({
       type: "POST",
       url: url,
       cache: false,
       success: function(response)
       {
		   	a.innerHTML= response;
       },
	
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
     });
}

function changeMa(id, url)
{
	var e = document.getElementById(id);
	var ma = $("#" + id).val();
	ma = ma.substring(1);

	url = url+ "?dmtk_matk="+ String(ma);
	x = e.parentNode;
	var a = x.getElementsByTagName('div')[0];


	jQuery.ajax({
       type: "POST",
       url: url,
       cache: false,
       success: function(response)
       {
		   	a.innerHTML= response;
       },
	
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
     });
}

function changeMaTQ(id, url)
{
	var e = document.getElementById(id);
	var ma = e.options[e.selectedIndex].text;
	url = url+ "?ma="+ ma;
	x = e.parentNode;
	var a = x.getElementsByTagName('div')[0];


	jQuery.ajax({
       type: "POST",
       url: url,
       cache: false,
       success: function(response)
       {
		   	a.innerHTML= response;
       },
	
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
     });
}

function ExitMa(id, aData)
{
	var kq = document.getElementById(id).value.toUpperCase() +"-";
	var pos = aData.indexOf(kq);

	if (pos <0 )
	{
		alert("Hay nhap ma dung!");
		document.getElementById(id).value = "";
		document.getElementById(id).focus();

	}
	else
	{
		document.getElementById(id).value = kq.substr(0,kq.length-1);
	}
}


function ExitMaCTTK(id, aDatadv, tkdvs, aDatacp, tkcps)
{
	var kq = document.getElementById(id).value.toUpperCase(); //+"-";
	kq	= kq.replace(/^\s+|\s+$/g, '');
	kq = kq +"-";
	idmatk = id.replace("chitiettkdu", "tkdu");
	matk = document.getElementById(idmatk).value;
	p = tkdvs.indexOf(matk+"-"); 

	if (p=0 || tkdvs.substr(p-1,1) == '-')   // tk loai cong no
	{
			var pos = aDatadv.indexOf(kq);
			if (pos <0 )
			{
				alert("Hay nhap ma don vi dung!");
				document.getElementById(id).value = "";
				document.getElementById(id).focus();
			}
			else
			{
				document.getElementById(id).value = kq.substr(0,kq.length-1);
			}
	}
	else 
	{
		p = tkcps.indexOf(matk+"-"); 
		if (p=0 || tkcps.substr(p-1,1) == '-')   // tk loai chi phi
		{
			var pos = aDatacp.indexOf(kq);
			if (pos <0 )
			{
				alert("Hay nhap ma chi phi dung!");
				document.getElementById(id).value = "";
				document.getElementById(id).focus();

			}
			else
			{
				document.getElementById(id).value = kq.substr(0,kq.length-1);
			}
		}
		else
		{   // tk khong chi tiet
			if (kq.length >0)
			{
				alert("Day la TK khong chi tiet");
				document.getElementById(id).value = "";

			}

		}
	}

}


function zExitMa(id, idHint, aData)
{
	var x=document.getElementById(id);
	x = x.parentNode;


	var a = x.getElementsByTagName('div')[0];
	var stk, astk, pos;
	var kq = document.getElementById(id).value.toUpperCase();
	

	//aData = aData.replace(sbold, "");
	//aData = aData.replace(ebold, "");
	dmtk = aData.split(",");
	

	for (i = 0; i < dmtk.length; ++i) 
	{ 
		stk = dmtk[i].toUpperCase();
		pos = stk.indexOf(kq);
		if (pos ==0 )
		{
			astk = stk.split("-");
			document.getElementById(id).value = astk[0];
			//document.getElementById(idHint).innerHTML  =  astk[1];
			a.innerHTML  =  astk[1].toLowerCase();;
			return;
		}
	}
	alert("Hay nhap ma dung ka dsadsad");
	document.getElementById(id).value = kq;
	document.getElementById(id).focus();
	//document.getElementById(idHint).innerHTML  =  "Hay nhap ma dung";
	a.innerHTML  =  "Hay nhap ma dung";
}


//function ShowHintCTTK(q,aDataLoaiTK, aDataDV, aDataCP, txtMa, ngandong )
function zExitMaCTTK(id, aDataLoaiTK, aDataDV, aDataCP)
{

	currentid = id;
	var x=document.getElementById(id);
	x = x.parentNode;
	var a = x.getElementsByTagName('div')[0];

	var stk, astk, pos;
	var kq = document.getElementById(id).value.toUpperCase();

	/// loai tai khoan:
	//lay tai khoan du:
	var idmatk = id.replace("chitiettkdu", "tkdu");
	var idmatk_value =document.getElementById(idmatk).value;

	if (idmatk_value.length == 0)
	{
		document.getElementById(txtMa).value = "";
		//document.getElementById(idmatk).focus();
		a.innerHTML= "";
		return;
	}

	/// lay danh muc tuong ung
	dmtkLoai = aDataLoaiTK.split(",");
	var inpos = dmtkLoai.indexOf(idmatk_value+"-DV");
	if (inpos>=0)
	{
		aDataDV = aDataDV.replace(sbold, "");
		aDataDV = aDataDV.replace(ebold, "");
		dmtk = aDataDV.split(",");
	}
	else 
	{
		inpos = dmtkLoai.indexOf(idmatk_value+"-CP");
		if (inpos>=0)
		{
			aDataCP = aDataCP.replace(sbold, "");
			aDataCP = aDataCP.replace(ebold, "");
			dmtk = aDataCP.split(",");
		}
		else
		{
			document.getElementById(txtMa).value = "";
			//document.getElementById(idsotienvn).focus();
			a.innerHTML= "";
			return;

		}

	}

	
	
	for (i = 0; i < dmtk.length; ++i) 
	{ 
		stk = dmtk[i].toUpperCase();
		pos = stk.indexOf(kq);
		if (pos==0)
		{
			astk = stk.split("-");
			document.getElementById(id).value = astk[0];
			//document.getElementById(idHint).innerHTML  =  astk[1];
			a.innerHTML  =  astk[1].toLowerCase();;
			return;
		}
	}

	alert("Hay nhap ma dung");
	document.getElementById(id).value = kq;
	document.getElementById(id).focus();
	//document.getElementById(idHint).innerHTML  =  "Hay nhap ma dung";
	a.innerHTML  =  "Hay nhap ma dung";

}







function getMA(q, txtMa, txtHint)
{
	var subdata = q.split("-");

	document.getElementById(txtMa).value=subdata[0];
	document.getElementById(txtHint).innerHTML=subdata[1];

}

function testFieldNumber(field) {
    var regExpr = new RegExp("^\d*\.?\d*$");
    if (!regExpr.test(field)) {
      // Case of error
      field.value = "";
    }
}

function UpdateRecord(host, username, password, databaseName, year, urlupdate  )
  {
	  var matk=document.getElementById('matk').value;
	  var mant=document.getElementById('mant').value;
	  var madv = document.getElementById('madv').value;
	  var dknont = document.getElementById('dknont').value;
	  var dknovn = document.getElementById('dknovn').value;
      jQuery.ajax({
       type: "POST",
       url: urlupdate,
	   data: {host: host, username: username, password: password, databaseName: databaseName, year: year, matk:matk },
       cache: false,
       success: function(response)
       {
		
         alert("Ghi xong!");

       },
	
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
     });
  }




function PrintCT(idphieu, nam, noco, url)
{
	url = url+"?idphieu="+idphieu+"&&noco="+noco+"&&nam="+nam;
	var win = window.open(url, '_blank');
}

function PrintCT_CE(idphieu, nam, noco, url)
{
	if (idphieu=="")
	{
  		idphieu = $('div#idphieu').html();
		idphieu = idphieu.trim();
	}

	url = url+"?idphieu="+idphieu+"&&noco="+noco+"&&nam="+nam;
	var win = window.open(url, '_blank');
}

function InsCTTMTG(pnew, url, journalid,  year, mant, matk, mact, noco, urlupdate, urlmain, idphieu  )
{

	var dataMain = Array();
	var fieldMain = Array();
	var data = Array();
	var field = Array();


	$("#mymain").each(function(i, v){
		$(this).find('select').each(function(ii, vv){
			giatri = $("option:selected", this).text();
			//field = $("option:selected", this).name();
			giatri = giatri.split("::");
			dataMain[cot] = String(giatri[0]);
			fielMain[cot] = vv.id;
			alert(fielMain[cot]+"="+ dataMain[cot]);
			cot = cot+1;

		});

		$(this).find('input').each(function(ii, vv){
			if (cautruc[cot].indexOf("sotien") ==0)
			{
				var st = $(this).val();
				var st1 = parseFloat(st.replace(/,/g, ""));
				if (!isNaN(st1))
				{
					data[i][cot] = st1;
				}
				else
				{
					data[i][cot] = "";
				}
				cot = cot+1;
			}
			else
			{
			data[i][cot] = $(this).val();
			cot = cot+1;
			}
		}); 
	})

	return;

	 if ($("input#save").val() == "Thêm mới")
	 {
		 ngct = $('input#ngct').val();
		 $('input:text').attr("value", "");
		 $('input#ngct').attr("value", ngct);

		 $('input#print').attr("disabled", true);
		 $('input#save').attr("value", "Ghi lại");
		 $('input#edit').attr("disabled", true);
		 $("select.selectMenu").attr('selectedIndex',0);
		 $("select.selectMenu2").attr('selectedIndex',0);
		 $('div.selectMenu').html("");
		 document.getElementById("total").innerHTML = "";
		 if ($("#totalNT").length){ // do something here }
			document.getElementById("totalNT").innerHTML = "";
		 }

		 var x=document.getElementById('myDetail');
		 var a = x.getElementsByTagName('a');
		 var sd = a.length ;
		 for (i=2;i<sd ; i++){
				document.getElementById("myDetail").deleteRow(3);
		
		 }

		 document.getElementById('soct').focus();
		 return;
	 }

	if (pnew == 'new')
		{
			var win = window.open(url, '_blank');
		}
		var data = Array();
		var cautruc = Array();

		var soct=document.getElementById('soct').value;
		var ngct=document.getElementById('ngct').value;

			var dt1   = parseInt(ngct.substring(0,2));
			var mon1  = parseInt(ngct.substring(3,5));
			var yr1   = parseInt(ngct.substring(6,10));
			if (yr1 != year)
			{
				alert("Ban nhap nam chua dung!");
				document.getElementById('ngct').focus();
				return;
			}
			var ngay = yr1+"-"+ mon1+"-" + dt1;
//			var a= "";
//			try {
//			 testdate = $.datepicker.parseDate('yy-mm-dd', ngay);
//			 //alert(testdate);
//			} catch (e)
//			{
//			 alert('Ban nhap ngay ' + ngay  + ' khong dung.' );
//			 return;
//			}

			ngct = ngay;


		var hoten=document.getElementById('hoten').value;

		var diachi=document.getElementById('diachi').value;
		var lydo=document.getElementById('lydo').value;
		var emadv = document.getElementById('madv');
		var madv = "";

		if ( emadv != null)
		{
			madv = emadv.value;
		}

		var solgctg= document.getElementById('solgctg').value;

		var etygia = document.getElementById('tygia');
		var tygia = "";
		if ( etygia != null)
		{
			tygia = etygia.value;
		}

		matkas = $("#matk option:selected").text();
		matka = matkas.split("-");
		matk =matka[0];

//		var mant=document.getElementById('mant').value;
//		var madv = document.getElementById('madv').value;
//		var dknont = document.getElementById('dknont').value;
//		var dknovn = document.getElementById('dknovn').value;

		$(".myheaderrow").each(function(i, v){
			$(this).find('th').each(function(ii, vv){
				cautruc[ii] = $(this).attr("name");
			}); 
		})



		$(".mydatarow").each(function(i, v){
			data[i] = Array();
			cot = 0;
			$(this).find('select').each(function(ii, vv){
				giatri = $("option:selected", this).text();
				giatri = giatri.split("::");
				data[i][cot] = String(giatri[0]);
				cot = cot +1;
			});

			$(this).find('input').each(function(ii, vv){
				if (cautruc[cot].indexOf("sotien") ==0)
				{
					var st = $(this).val();
					var st1 = parseFloat(st.replace(/,/g, ""));
					if (!isNaN(st1))
					{
						data[i][cot] = st1;
					}
					else
					{
						data[i][cot] = "";
					}
					cot = cot+1;
				}
				else
				{
				data[i][cot] = $(this).val();
				cot = cot+1;
				}
			}); 
		})


	jQuery.ajax({
       type: "POST",
       url: urlupdate,
	   data: {host: host, username: username, password: password, databaseName: databaseName, journalid:journalid,  year:year,  tableArr: data, cautruc: cautruc, soct: soct, ngct: ngct, hoten:hoten, diachi: diachi, lydo: lydo, madv: madv, solgctg: solgctg, tygia: tygia, matk: matk, mant: mant, mact:mact, noco:noco, idphieu: idphieu},
       cache: false,
       success: function(response)
       {
		  //alert(response);
		 if (response == "2")
		 {
			 alert("Khong co du lieu!");
		 }
		 else if (response == "1")
		 {
			 alert("Co loi du lieu, mau tin khong ghi duoc!");

		 }
		 else 
		   {
			 if (idphieu == "")
			 {
				 $('div#idphieu').html(response);
				 $('input#print').attr("disabled", false);
				 $('input#save').attr("value", "Thêm mới");
			 }
			 else
			   {
				// alert("Da ghi xong!");
		   }
			$('div#action').html("Xem chứng từ");
			$('input#save').attr("value", "Thêm mới");
			$('input#edit').attr("disabled", false);
			$('input#edit').attr("value", "Sửa");
		   }
       },
	
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
     });


  }

function Edit_1CT(){
	 
	editmode = $('input#edit').val();
	idphieu = $('div#idphieu').html();
	if (idphieu = ""){
			$('input#save').attr("value", "Ghi lại");
			$('input#edit').attr("disableb", true);
			$('div#action').html("Thêm chứng từ");
		}else 
		if (editmode == "Sửa"){
			$('input#save').attr("value", "Ghi lại");
			$('input#edit').attr("value", "Thôi sửa");
			$('div#action').html("Sửa chứng từ");
		}
		else
		{
			$('input#save').attr("value", "Thêm mới");
			$('input#edit').attr("value", "Sửa");
			$('div#action').html("Xem chứng từ");

		}
	
}



function editCT(idPhieu, url)
{
	url = url + "&idPhieu=" + encodeURIComponent(idPhieu);
	location.href = url;
	//var win = window.open(url, '_blank');

}

function refurl(url)
{
	location.href = url;

}

function deleCT(host, username, password, databaseName, journalid,  year, idPhieu, soct, url, urlRFR)
{
	if (!(confirm("Ban muon xoa chung tu"+ soct+"  khong?")))
	{
		return;
	}
	var x=document.getElementById('customers');
	for (i=1;i< x.rows.length ; i++)
	{
		var row = x.rows[i];
		var a1 = row.getElementsByTagName('a')[0];
		if (idPhieu == a1.id)
		{
			document.getElementById("customers").deleteRow(i);
		}
	}

	jQuery.ajax({
       type: "POST",
       url: url,
	   data: {host: host, username: username, password: password, databaseName: databaseName, journalid: journalid, year:year,  idPhieu:idPhieu},
       cache: false,
       success: function(response)
       {
		   location.href = urlRFR;
       },
	
	   error: function(data, errorThrown)
	  {
		  alert('request failed :'+errorThrown);
	  }
     });
	return;

}

